var geolocation;
$(function () {
    geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 1000       //超过10秒后停止定位，默认：5s
        // GeoLocationFirst: true
    });
    if (localStorage.getItem('deviceLocation') === null || localStorage.getItem('deviceLocation') === '') {
        $('a.city').text('未定位');
    } else {
        $('a.city').text(localStorage.getItem('deviceLocation'));
    }
})

function detectLocation() {
    //如果设置与获取的不符则
    let city;
    geolocation.getCurrentPosition(function (status, result) {
        if (status === 'complete') {
            // 直辖市判断
            if (result.addressComponent.city === '' || result.addressComponent.city === undefined || result.addressComponent.city.length === 0) {
                city = result.addressComponent.province;
            } else {
                city = result.addressComponent.city;
            }
            // 本地缓存判断
            if (localStorage.getItem('deviceLocation') != city || localStorage.getItem('deviceLocation') === '') {
                layer.open({
                    skin: 'confirm-skin',
                    title: false,
                    content: '检测您的当前位置,是否切换至【' + city + '】?',
                    closeBtn: false, btn: ['是', '否'],
                    yes: function (index, layero) {
                        localStorage.setItem('deviceLocation', city);
                        $('a.city').text(city);
                        layer.closeAll('dialog');
                    },
                    btn2: function (index, layero) {
                        //按钮【按钮二】的回调
                    },
                    success: function () {
                    }
                });
            } else {
                $('a.city').text(city);
            }
        } else {
            layer.msg("获取定位失败")
        }
    });
}

function selfLocation() {
    let city;
    geolocation.getCurrentPosition(function (status, result) {
        if (status === 'complete') {
            if (result.addressComponent.city === '' || result.addressComponent.city === undefined || result.addressComponent.city.length === 0) {
                $('a.city').text(result.addressComponent.province);
            } else {
                $('a.city').text(result.addressComponent.city);
            }
        } else {
            layer.msg("获取定位失败")
        }
    });
}